package gift.justflower.ecp.controller;

import gift.justflower.ecp.bean.Goods;
import gift.justflower.ecp.bean.Type;
import gift.justflower.ecp.bean.User;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import java.util.List;
import java.util.Date;

/**
 * 货物相关方法
 * author：AB
 * time：2018年7月17日 23:05:16
 */
@IocBean
public class GoodsController {
    @Inject
    private Dao dao;

    @At("/goods/getById")
    @RequiresUser
    public Goods getById(@Param("id") String id) {
        return dao.fetch(Goods.class, id);
    }

    @At("/goods/del")
    @RequiresUser
    public NutMap del(@Param("id") String id) {
        dao.delete(Goods.class, id);
        return new NutMap("ok", true);
    }

    @At("/purchase")
    @Ok("beetl:/html/goods.html")
    @RequiresUser
    public void purchase(@Param("..") Pager pager) {
        if (null == pager) {
            pager = new Pager();
            pager.setPageNumber(1);
            pager.setPageSize(20);
        }
        User user = (User) Mvcs.getHttpSession().getAttribute("user");
        pager.setRecordCount(dao.count(Goods.class, Cnd.where("userId", "=", user.getId())));
        List<Goods> goodsList = dao.query(Goods.class, Cnd.where("userId", "=", user.getId()).desc("createTime"), pager);
        Mvcs.getReq().setAttribute("queryResult", new QueryResult(goodsList, pager));
        Mvcs.getReq().setAttribute("types", dao.query(Type.class, Cnd.where("userId", "=", user.getId())));
    }

    @At("/goods/add")
    @Ok(">>:/purchase")
    @RequiresUser
    public void add(@Param("..") Goods goods) {
        User user = (User) Mvcs.getHttpSession().getAttribute("user");
        goods.setUserId(user.getId());
        if (Strings.isEmpty(goods.getId())) {
            goods.setCreateTime(new Date());
            goods.setStock(goods.getCount());
            dao.insert(goods);
        } else {
            dao.updateIgnoreNull(goods);
        }

        Type type = dao.fetch(Type.class, Cnd.where("name", "=", goods.getName()).and("userId", "=", user.getId()));

        if (null == type) {
            type = new Type();
            type.setName(goods.getName());
            type.setUserId(user.getId());
            dao.insert(type);
        }
    }
}
